package com.woniu.filter;

import com.alibaba.fastjson.JSON;
import com.woniu.util.JwtVerifyUtils;
import com.woniu.util.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * @author 李桢
 * @date 2021/3/31 17:11
 */

//@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    JwtVerifyUtils jwtVerifyUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        //如果请求认证中心直接放行
        URI uri = request.getURI();
        if (uri.toString().contains("auth")){
            return chain.filter(exchange);
        }

        //从请求头中获取token
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        //如果为空的话则没有登陆,返回通知前端
        if (StringUtils.isEmpty(token)) {
            ResultVO vo = new ResultVO(-5000, "Not logged in");
            String jsonString = JSON.toJSONString(vo);
            return sendResponseMessage(exchange, jsonString);

        }

        //如果有token的话去校验

        boolean flag = jwtVerifyUtils.verifyToken(token);

        //如果不合法，返回通知前端
        if (!flag) {
            ResultVO vo = new ResultVO(-7000, "Token illegal");
            String jsonString = JSON.toJSONString(vo);
            return sendResponseMessage(exchange, jsonString);
        }

        //所有认证完毕，token合法，放行
        return chain.filter(exchange);
    }


    /*
    * 此方法用来加工返回信息，使其符合filter方法中Mono类型的返回值
    * */
    public static Mono<Void> sendResponseMessage(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bits = message.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        return response.writeWith(Mono.just(buffer));
    }

    /*
     * 标识当前过滤器的优先级，返回的数字越小，优先级越高
     * */
    @Override
    public int getOrder() {
        return 0;
    }
}
